<template>
  <section class="page-content">
    <el-tabs value="basic" @tab-click="handleClick" type="border-card">
      <el-tab-pane label="基本信息" name="basic">
        <el-form size="medium" :model="goodsData" :rules="rules" ref="goodsData" label-width="100px" class="form-goods-basic">
          <el-form-item label="产品名称" prop="name">
            <el-input v-model="goodsData.name"></el-input>
          </el-form-item>
          <el-form-item label="数量单位" prop="unit">
            <el-input v-model="goodsData.unit"></el-input>
          </el-form-item>
          <el-form-item label="产品原价" prop="original_price">
            <el-input v-model.number="goodsData.original_price"></el-input>
          </el-form-item>
          <el-form-item label="产品售价" prop="price" >
            <el-input v-model.number="goodsData.price"></el-input>
          </el-form-item>
          <el-form-item label="库存数量" prop="stock">
            <el-input type="number" v-model="goodsData.stock"></el-input>
          </el-form-item>
          <el-form-item label="赠送积分" prop="give_integral">
            <el-input type="number" v-model="goodsData.give_integral"></el-input>
          </el-form-item>
          <el-form-item label="兑换积分" prop="exchange_integral">
            <el-input type="number" v-model="goodsData.exchange_integral"></el-input>
          </el-form-item>
          <el-form-item label="起始销量" prop="start_sales_count">
            <el-input type="number" v-model="goodsData.start_sales_count"></el-input>
          </el-form-item>
          <el-form-item label="产品排序" prop="order">
            <el-input type="number" v-model="goodsData.order"></el-input>
          </el-form-item>
          <el-form-item label="产品分类" prop="category_id">
            <el-select v-model.number="goodsData.category_id" placeholder="请选择所属分类">
              <el-option v-for="category in categories" :key="category.id" :label="category.name" :value="category.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="一级提成" prop="bonus_ratio_1">
            <el-input v-model="goodsData.bonus_ratio_1"></el-input>
          </el-form-item>
          <el-form-item label="二级提成" prop="bonus_ratio_2">
            <el-input v-model="goodsData.bonus_ratio_2"></el-input>
          </el-form-item>
          <el-form-item label="缩略图" prop="thumb_img">
            <el-upload
              class="thumb-uploader"
              :action="$serverUrl + '/api/upload/image'"
              :data="{width: 300, height: 300, folder: 'goods'}"
              accept="image/*"
              :show-file-list="false"
              :on-success="handleThumbUploadSuccess"
              :before-upload="beforeThumbUpload">
              <img v-if="goodsData.thumb_img" :src="thumb" class="thumb-img">
              <i v-else class="el-icon-plus thumb-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="是否上架" prop="is_on_sale">
            <el-switch v-model="goodsData.is_on_sale"></el-switch>
          </el-form-item>
          <el-form-item label="产品属性">
              <el-checkbox label="新品" name="is_new" v-model="goodsData.is_new"></el-checkbox>
              <el-checkbox label="热销" name="is_hot" v-model="goodsData.is_hot"></el-checkbox>
              <el-checkbox label="精品" name="is_best" v-model="goodsData.is_best"></el-checkbox>
              <el-checkbox label="虚拟商品" name="is_virtual" v-model="goodsData.is_virtual"></el-checkbox>
              <el-checkbox label="积分商品" name="is_exchange" v-model="goodsData.is_exchange"></el-checkbox>
          </el-form-item>
          <el-form-item label="可用轻币数" prop="qingbi_number" v-if="goodsData.is_exchange">
            <el-input v-model="goodsData.qingbi_number"></el-input>
          </el-form-item>
          <el-form-item label="关键词" prop="keywords">
            <el-input v-model="goodsData.keywords"></el-input>
          </el-form-item>
          <el-form-item label="产品描述" prop="description">
            <el-input type="textarea" v-model="goodsData.description"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button :loading="loading" type="primary" @click="submitgoodsData('goodsData')">保存</el-button>
            <el-button @click="resetForm('goodsData')">重置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="详细信息" name="body">
        <tinymce :height="500" v-model="goodsData.content.body" v-if="goodsData.content"></tinymce>
        <el-form>
         <el-form-item class="form-goods-body">
            <el-button type="primary" :disabled="!isEdit" @click="submitGoodsContent()">保存</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="产品模型" name="attr">
        <goods-attr ref="goodsAttr" :goods="goodsData"></goods-attr>
      </el-tab-pane>
      <el-tab-pane label="满减优惠" name="fullCut">
        <full-cut ref="fullCut" :goods="goodsData"></full-cut>
      </el-tab-pane>
      <el-tab-pane label="产品相册" name="gallery">
        <el-alert
          style="margin-bottom:20px;"
          :title="'图片大小不能超过 '+ attachmentSize + ' M；最能能添加 ' + attachmentLimit + ' 张图片；推荐图片尺寸 ' + attachmentWidth + 'x' + attachmentHeight + 'px'"
          type="warning"
          show-icon>
        </el-alert>
        <el-upload
          :action="$serverUrl + '/api/upload/attachment'"
          list-type="picture-card"
          :limit="attachmentLimit"
          :accept="'image/*'"
          :file-list="goodsData.attachments"
          :disabled="!isEdit"
          :on-preview="handlePictureCardPreview"
          :before-upload="beforeAttachmentUpload"
          :on-success="attachmentUploadSuccess"
          :on-remove="handleRemove"
          :on-exceed="handleExceed"
          :data="{attachmentable_type: 'App\\Goods', attachmentable_id: goodsData.id, width: attachmentWidth, height: attachmentHeight}">
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-tab-pane>
    </el-tabs>
  </section>
</template>

<script>
  import Tinymce from '@/components/tinymce/Editor'
  import GoodsAttr from '@/views/goods/components/GoodsAttr'
  import FullCut from '@/views/goods/components/FullCut'
  export default {
    name: 'goods',
    data () {
      return {
        loading: false,
        visible: false,
        dialogImageUrl: '',
        dialogVisible: false,
        categories: [],
        attachmentSize: 1,
        attachmentLimit: 5,
        attachmentWidth: 800,
        attachmentHeight: 800,
        tempData: {
          id: null,
          name: '',
          unit: '',
          content: {
            body: ''
          },
          attrs: [],
          attachments: [],
          category_id: '',
          original_price: '',
          give_integral: 0,
          exchange_integral: 0,
          thumb_img: '',
          original_img: '',
          price: '',
          stock: 9999,
          full_cut: null,
          start_sales_count: 0,
          order: 100,
          is_on_sale: false,
          is_new: true,
          is_hot: true,
          is_best: true,
          is_virtual: false,
          is_exchange: false,
          qingbi_number: 0,
          keywords: '',
          bonus_ratio_1: 0.00,
          bonus_ratio_2: 0.00,
          description: ''
        },
        goodsData: {},
        rules: {
          name: [
            { required: true, message: '请输入产品名称', trigger: 'blur' },
            { min: 1, max: 250, message: '长度在1到250个字符', trigger: 'blur' }
          ],
          category_id: [
            { required: true, type: 'number', message: '请选择产品分类', trigger: 'change' }
          ],
          thumb_img: [
            { required: true, message: '请上传缩略图', trigger: 'blur' }
          ],
          unit: [
            { required: true, message: '该字段必填', trigger: 'blur' },
            { min: 1, max: 5, message: '长度在 1 到 5 个字符', trigger: 'blur' }
          ],
          original_price: [
            { type: 'number', required: true, message: '该字段必填', trigger: 'blur' }
          ],
          price: [
            { type: 'number', required: true, message: '该字段必填', trigger: 'blur' }
          ],
          bonus_ratio_1: [
            { required: true, message: '该字段必填', trigger: 'blur' }
          ],
          bonus_ratio_2: [
            { required: true, message: '该字段必填', trigger: 'blur' }
          ],
          resource: [
            { required: true, message: '请选择产品资源', trigger: 'change' }
          ],
          desc: [
            { required: true, message: '请填写产品形式', trigger: 'blur' }
          ]
        }
      }
    },
    components: { Tinymce, GoodsAttr, FullCut },
    methods: {
      handleThumbUploadSuccess (res, file) {
        console.log(res)
        // this.goodsData.content = URL.createObjectURL(file.raw)
        this.goodsData.thumb_img = res.thumb_img
        this.goodsData.original_img = res.original_img
      },
      beforeThumbUpload (file) {
        const sizeLimit = file.size / 1024 / 1024 < 0.5
        if (!sizeLimit) {
          this.$message.error('上传图片大小不能超过0.5MB!')
        }
        return sizeLimit
      },
      handleClick (tab, event) {
        console.log(tab, event)
      },
      submitgoodsData (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this._createOrEditgoodsData()
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      submitGoodsContent () {
        this.loading = true
        if (!this.isEdit) {
          this.$message.error('请先提交产品基本信息')
        }
        this.$http.put('/goods/' + this.goodsData.id, {content: {body: this.goodsData.content.body}})
        .then((response) => {
          this.loading = false
          this.$message.success('保存成功')
        }).catch((error) => {
          this.loading = false
          console.log(error)
        })
      },
      resetForm (formName) {
        this.$refs[formName].resetFields()
      },
      handlePictureCardPreview (file) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      },
      beforeAttachmentUpload (file) {
        const sizeLimit = file.size / 1024 / 1024 < this.attachmentSize
        const isJPG = file.type === 'image/jpeg'
        const isPNG = file.type === 'image/png'
        if (!sizeLimit) {
          this.$message.error('上传附件大小不能超过' + this.attachmentSize + 'MB!')
          return false
        }
        if (!isJPG && !isPNG) {
          this.$message.error('只能上传png和jpg格式的文件')
          return false
        }
      },
      attachmentUploadSuccess (response, file, fileLis) {
        this.goodsData.attachments.push(response)
      },
      handleExceed (files, fileList) {
        this.$message.warning(`当前限制选择上传 ${this.attachmentLimit} 张图片`)
      },
      handleRemove (file, fileList) {
        if (!file.id) {
          return false
        }
        this._deleteAttachment('/attachments/' + file.id)
        this.goodsData.attachments.forEach((v, index, arr) => {
          if (v.id === file.id) {
            arr.splice(index, 1)
            return false
          }
        })
      },
      _deleteAttachment (url) {
        this.$http.delete(url).then((response) => {
          console.log(response)
        }).catch((error) => {
          console.log(error)
        })
      },
      _createOrEditgoodsData () {
        this.loading = true
        this.$http({
          method: this.isEdit ? 'put' : 'post',
          url: this.isEdit ? '/goods/' + this.goodsData.id : '/goods',
          data: this.goodsData
        }).then((response) => {
          this.loading = false
          this.$message.success('保存成功')
          this.$router.push('/goods/edit/' + response.data.id)
        }).catch((error) => {
          this.loading = false
          console.log(error)
        })
      },
      _resetGoodsData () {
        this.goodsData = Object.assign({}, this.tempData)
      },
      _getData () {
        this.$http.get('/goods/' + this.$route.params.id + '/edit').then((response) => {
          this.goodsData = response.data
          this.$refs.goodsAttr.getAttrs(response.data.type_id, response.data.id)
        }).catch((error) => {
          console.log(error)
        })
      },
      _getCategories () {
        this.$http.get('/categories?belongs_to=goods&data_type=tree').then((response) => {
          this.categories = response.data
        }).catch((error) => {
          console.log(error)
        })
      }
    },
    computed: {
      isEdit () {
        return this.$route.meta.isEdit
      },
      thumb () {
        if (this.goodsData.thumb_img.indexOf('http:') === -1) {
          return this.$serverUrl + '/storage/' + this.goodsData.thumb_img
        }
        return this.goodsData.thumb_img
      }
    },
    watch: {
      '$route' (to, from) {
        if (!to.meta.isEdit) {
          this._resetGoodsData()
        } else {
          this._getData()
        }
      }
    },
    mounted () {
      this._resetGoodsData()
      this._getCategories()
      if (this.isEdit) {
        this._getData()
      }
    }
  }
</script>
<style scoped lang="scss">
  .form-goods-basic {
    width: 700px;
    .el-select {
      width: 100%;
    }
  }
  .form-goods-body {
    margin-top: 20px;
  }
  .thumb-uploader, .thumb-uploader-icon, .thumb-img{
    width: 200px;
    height: 200px;
  }
  .thumb-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    overflow: hidden;
    &:hover {
      border-color: #20a0ff;
    }
    .thumb-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      line-height: 200px;
      text-align: center;
      &:hover {
        color: #20a0ff;
      }
    }
  }
  .dialog {
      .el-input {
        width: 100%;
      }
      .el-select {
        width: 100%;
      }
    } 
</style>